/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.paycallback;

import org.zhiqim.account.dao.UserTradeDao;
import org.zhiqim.account.dbo.user.UserInfo;
import org.zhiqim.account.dbo.user.UserTrade;
import org.zhiqim.account.dbo.user.UserTradeAlipay;
import org.zhiqim.account.dbo.user.UserTradeWxpay;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.orm.ZTable;

/**
 * 支付（账户充值）
 *
 * @version v1.4.1 @author zouzhigang 2018-4-25 新建与整理
 */
@AnAlias("PayAccount")
public class PayAccount implements PayCallback
{
    private static final Log log = LogFactory.getLog(PayAccount.class);
    
    @Override
    public void call(UserTradeWxpay wxpay) throws Exception
    {
          long tradeId = wxpay.getTradeId();
          
          UserTrade trade = Global.get(ZTable.class).item(UserTrade.class, tradeId);
          if (trade != null)
          {//已处理充值的不再处理
              log.info("收到微信交易通知["+wxpay.getTradeNo()+"]无需更新");
          }
          else
          {//更新用户账户
              UserInfo user = UserTradeDao.doCharge(wxpay);
              log.info("收到微信通知更新,用户["+user.getUserNick() +"]更新交易明细");
          }
    }

    @Override
    public String call(UserTradeAlipay alipay, boolean notify) throws Exception
    {
        long tradeId = alipay.getTradeId();
        String type = notify?"通知":"返回";
        
        UserTrade trade = Global.get(ZTable.class).item(UserTrade.class, tradeId);
        if (trade != null)
        {//已处理，不再处理
            log.info("收到支付宝交易"+type+"["+alipay.getTradeNo()+"]["+alipay.getTradeStatus()+"]无需更新");
        }
        else
        {//未处理，插入交易明细，修改用户余额，完成充值
            UserInfo user = UserTradeDao.doCharge(alipay);
            log.info("收到支付宝"+type+"更新,用户["+user.getUserNick() +"]更新交易明细");
        }
        
        return "/account/index.htm";
    }

    @Override
    public String call(UserTrade balancePay) throws Exception
    {
        return "/account/index.htm";
    }
}
